﻿/* ============================================================================== 
 * 功能描述：BTManager 
 * 创 建 者：Administrator
 * 创建日期：2016/4/29 10:37:38 
 * ==============================================================================*/

using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using ZZQFrameWork.AI;
using ZZQFrameWork.AI.BT;

    public class BTManager : Singleton<BTManager>
    {
        private Dictionary<uint, BehaviorTreeRoot> btDic = new Dictionary<uint, BehaviorTreeRoot>();

        public override void Init()
        {
            Assembly ass = typeof(BTManager).Assembly; //获取所有的程序集
            var types = ass.GetTypes(); //获取所有的程序集类型
            foreach (var item in types)
            {
                //如果程序集命名空间为BT，并且基类是BTRoot
                if (item.Namespace == "ZZQFrameWork.AI.BT")
                {
                    var type = item.BaseType;
                    if (type == typeof(ZZQFrameWork.AI.BehaviorTreeRoot))
                    {
                        string id = item.Name.Replace("BT", string.Empty); //根据该类的名称，获取到最后的编号
                        uint aiId;
                        if (uint.TryParse(id, out aiId)) //把编号转换为uint
                        {
                            var p = item.GetProperty("Instance"); //获取程序集的Instance属性
                            var v = p.GetGetMethod().Invoke(null, null) as BehaviorTreeRoot; //调用Instance属性的实例化
                            btDic.Add(aiId, v);
                        }
                    }
                }
            }
        }

        public static BehaviorTreeRoot Get(uint id)
        {
            return Instance.GetRoot(id);
        }

        public BehaviorTreeRoot GetRoot(uint id)
        {
            if (btDic.ContainsKey(id)) return btDic[id];
            return null;
        }
    }
